summaryrefslogtreecommitdiff
path: root/app/[lng]/partners/(partners)/rfq-last/[id]/page.tsx
blob: 9052de6f9b57643f4a8bf281869c55e37b1ff410 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
// app/partners/rfq-last/[id]/page.tsx
import { Metadata } from "next"
import { notFound } from "next/navigation"
import db from "@/db/db"
import { eq, and } from "drizzle-orm"
import { 
  rfqsLast, 
  rfqLastDetails, 
  rfqLastVendorResponses,
  rfqPrItems,basicContractTemplates,basicContract,
  vendors 
} from "@/db/schema"
import { getServerSession } from "next-auth/next"
import { authOptions } from "@/app/api/auth/[...nextauth]/route"
import VendorResponseEditor from "@/lib/rfq-last/vendor-response/editor/vendor-response-editor"

interface PageProps {
  params: {
    id: string
  }
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  return {
    title: "견적서 작성",
    description: "RFQ에 대한 견적서 작성 및 제출",
  }
}

export default async function VendorResponsePage({ params }: PageProps) {
  const rfqId = parseInt(params.id)
  
  if (isNaN(rfqId)) {
    notFound()
  }
  
  // 인증 확인
  const session = await getServerSession(authOptions)
  
  if (!session?.user) {
    return (
      <div className="flex h-full items-center justify-center">
        <div className="text-center">
          <h2 className="text-xl font-bold">로그인이 필요합니다</h2>
          <p className="mt-2 text-muted-foreground">견적서 작성을 위해 로그인해주세요.</p>
        </div>
      </div>
    )
  }
  
  // 벤더 정보 가져오기
  const vendor = await db.query.vendors.findFirst({
    where: eq(vendors.id, session.user.companyId)
  })
  
  if (!vendor || session.user.domain !== "partners") {
    return (
      <div className="flex h-full items-center justify-center">
        <div className="text-center">
          <h2 className="text-xl font-bold">접근 권한이 없습니다</h2>
          <p className="mt-2 text-muted-foreground">벤더 계정으로 로그인해주세요.</p>
        </div>
      </div>
    )
  }

  console.log(vendor,"vendor")
  
  // RFQ 정보 가져오기
  const rfq = await db.query.rfqsLast.findFirst({
    where: eq(rfqsLast.id, rfqId),
    with: {
      project: true,
      rfqDetails: {
        where: and(eq(rfqLastDetails.vendorsId, vendor.id),eq(rfqLastDetails.isLatest, true)),
        with: {
          vendor: true,
          paymentTerms: true,
          incoterms: true,
        }
      },
      rfqPrItems: true,
    }
  })
  
  if (!rfq || !rfq.rfqDetails[0]) {
    notFound()
  }

  // 취소된 RFQ 접근 제어
  if (rfq.status === "RFQ 삭제") {
    return (
      <div className="flex h-full items-center justify-center">
        <div className="text-center max-w-md">
          <h2 className="text-xl font-bold">접근 불가</h2>
          <p className="mt-2 text-muted-foreground">이 RFQ는 삭제되어 접근할 수 없습니다.</p>
            <div className="mt-4 p-4 bg-muted rounded-lg text-left">
              <p className="text-sm font-medium mb-2">삭제 사유:</p>
              <p className="text-sm text-muted-foreground whitespace-pre-wrap">{rfq.deleteReason}</p>
            </div>
          
        </div>
      </div>
    )
  }
  
  const rfqDetail = rfq.rfqDetails[0]

  // 기존 응답 가져오기 (있는 경우)
  const existingResponse = await db.query.rfqLastVendorResponses.findFirst({
    where: and(
      eq(rfqLastVendorResponses.rfqsLastId, rfqId),
      eq(rfqLastVendorResponses.vendorId, vendor.id),
      eq(rfqLastVendorResponses.isLatest, true)
    ),
    with: {
      quotationItems: true,
      attachments: true,
      priceAdjustmentForm: true,
    }
  })

  // 취소된 RFQ 접근 제어 (vendor response가 취소 상태인 경우)
  if (existingResponse?.status === "취소" || rfqDetail.cancelReason) {
    return (
      <div className="flex h-full items-center justify-center">
        <div className="text-center">
          <h2 className="text-xl font-bold">RFQ 취소됨</h2>
          <p className="mt-2 text-muted-foreground">
            이 RFQ는 취소되어 더 이상 견적을 제출할 수 없습니다.
          </p>
          {rfqDetail.cancelReason && (
            <p className="mt-4 text-sm text-muted-foreground">
              취소 사유: {rfqDetail.cancelReason}
            </p>
          )}
        </div>
      </div>
    )
  }
  
  // PR Items 가져오기
  const prItems = await db.query.rfqPrItems.findMany({
    where: eq(rfqPrItems.rfqsLastId, rfqId),
    orderBy: (items, { asc }) => [asc(items.rfqItem)]
  })

  const basicContracts = await db
  .select({
    id: basicContract.id,
    // templateId: basicContract.templateId,
    templateName: basicContractTemplates.templateName,
    status: basicContract.status,
    // fileName: basicContract.fileName,
    // filePath: basicContract.filePath,
    deadline: basicContract.deadline,
    signedAt: basicContract.vendorSignedAt,
    // rejectedAt: basicContract.rejectedAt,
    // rejectionReason: basicContract.rejectionReason,
    createdAt: basicContract.createdAt,
  })
  .from(basicContract)
  .leftJoin(
    basicContractTemplates,
    eq(basicContract.templateId, basicContractTemplates.id)
  )
  .where(
    and(
      eq(basicContract.vendorId, vendor.id),
      eq(basicContract.rfqCompanyId, rfqDetail.id)
    )
  )
  .orderBy(basicContract.createdAt)

  
  return (
    <div className="container mx-auto py-8">
      <VendorResponseEditor
        rfq={rfq}
        rfqDetail={rfqDetail}
        prItems={prItems}
        vendor={vendor}
        existingResponse={existingResponse}
        userId={session.user.id}
        basicContracts={basicContracts} // 추가

      />
    </div>
  )
}